package com.chromatic.messages.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
    // 定义一个volatile变量来控制服务器是否继续运行
    private volatile boolean running = true;

    // 启动服务的方法，参数是监听的端口号
    public void start(int port) {
        try (ServerSocket serverSocket = new ServerSocket(port)) { // 使用try-with-resources启动ServerSocket
            while (running) { // 服务器将持续监听新的连接，直到running变量变为false
                try (Socket clientSocket = serverSocket.accept(); // 接受新的客户端连接
                     InputStream inputStream = clientSocket.getInputStream(); // 获取连接的输入流
                     OutputStream outputStream = clientSocket.getOutputStream()) { // 获取连接的输出流

                    int character;
                    StringBuilder data = new StringBuilder();

                    // 读取从客户端发送来的数据，直到连接关闭
                    while ((character = inputStream.read()) != -1) {
                        data.append((char) character);
                    }

                    // 打印接收到的信息
                    System.out.println("Received message: " + data + "from user_id 2 to user_id 1");

                    // 响应客户端
                    String response = "Received your message: " + data;
                    outputStream.write(response.getBytes());
                    outputStream.flush(); // 确保消息被立即发送

                } catch (IOException e) {
                    // 在处理客户端连接时捕获和处理IOException
                    System.out.println("Error handling client connection: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            // 在启动服务器时捕获和处理IOException
            System.out.println("Error starting server: " + e.getMessage());
        }
    }

    // 停止服务的方法，将running变量设置为false，从而导致服务器停止接收新的连接
    public void stop() {
        running = false;
    }
}